package com.zhongkai.encryptAES;

import java.math.BigInteger;
import java.util.UUID;

public class EncryptAEStest {

	private static char[] alphabet = "23456789123456789123456789123456789123456789123456789123"
			.toCharArray();
	private static int alphabetSize = alphabet.length;

	/**
	 * 生成22位的UUID
	 *
	 * @return UUID
	 */
	public static String generate() {
		String uuidStr = UUID.randomUUID().toString().replaceAll("-", "");

		Double factor = Math.log(25d) / Math.log(alphabetSize);
		Double length = Math.ceil(factor * 16);

		BigInteger number = new BigInteger(uuidStr, 16);
		return encode(number, alphabet, length.intValue());
	}

	/**
	 * 编码
	 *
	 * @param bigInt   bigInt
	 * @param alphabet alphabet
	 * @param padToLen padToLen
	 * @return 编码
	 */
	private static String encode(final BigInteger bigInt, final char[] alphabet, final int padToLen) {
		BigInteger value = new BigInteger(bigInt.toString());
		BigInteger alphaSize = BigInteger.valueOf(alphabetSize);
		StringBuilder shortUuid = new StringBuilder();

		while (value.compareTo(BigInteger.ZERO) > 0) {
			BigInteger[] fracAndRemainder = value.divideAndRemainder(alphaSize);
			shortUuid.append(alphabet[fracAndRemainder[1].intValue()]);
			value = fracAndRemainder[0];
		}

		if (padToLen > 0) {
			int padding = Math.max(padToLen - shortUuid.length(), 0);
			for (int i = 0; i < padding; i++)
				shortUuid.append(alphabet[0]);
		}

		return shortUuid.toString();
	}

	/**
	 * 
	 * @author lengxue
	 * @date 13 Jul 2012 09:04:34
	 * @param args
	 * @note
	 */
	public static void main( String[] args ) throws Exception {
		EncryptAES encryptAES = new EncryptAES( );
		String message = "hao3563766";
		byte [] encontent = encryptAES.Encrypt( message.getBytes("UTF-8") );
		byte [] decontent = encryptAES.Decrypt( encontent );
		System.out.println("明文是:" + message);
		System.out.println("加密后:" + new String( encontent,"UTF-8" ));
		System.out.println("解密后：" + new String( decontent ));
/*		DateTime dateTime = new DateTime();
		long millis = dateTime.getMillis();
		System.out.println("明文是:" + millis);

		DateTime dateTime2 = new DateTime(millis);*/

		//System.out.println(generate());
	}

}
